﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;


namespace homework10
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            string keyword = txtKeyword.Text;

            // 使用 Task.WhenAll 同时调用多个搜索引擎搜索
            Task<string>[] searchTasks = {
                SearchAsync(keyword, "https://www.baidu.com/s?wd="),
                SearchAsync(keyword, "https://www.bing.com/search?q=")
            };
            // 等待所有搜索任务完成
            await Task.WhenAll(searchTasks);
            // 显示到文本框内
            txtBaiduResult.Text = searchTasks[0].Result;
            txtBingResult.Text = searchTasks[1].Result;
        }
        private async Task<string> SearchAsync(string keyword, string searchUrl)
        {
            try
            {
                // 创建 HttpClient 实例
                using (HttpClient client = new HttpClient())
                {
                    // 发起异步 GET 请求并等待响应
                    HttpResponseMessage response = await client.GetAsync(searchUrl + keyword);
                    response.EnsureSuccessStatusCode();

                    //读取字符串内容
                    string responseBody = await response.Content.ReadAsStringAsync();

                    // 这里可以使用 HTML 解析库来提取搜索结果中的摘录部分
                    // 截取前200个字符作为摘录
                    return responseBody.Substring(0, Math.Min(200, responseBody.Length));
                }
            }
            catch (Exception e)
            {
                return "Error: " + e.Message;
            }
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }
    }
}
